package moe.oil.db.api;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import moe.oil.db.service.UserService;
import moe.oil.dto.user.UserDTO;
import moe.oil.exception.user.UserLoginErrorException;
import moe.oil.exception.user.UsernameExistException;
import moe.oil.exception.user.UsernameNotFoundException;
import moe.oil.validation.grop.OnInsert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * author: 紫月
 * Date: 2022/04/15 21:24
 * Description:
 *
 * @author zyz
 */

@RestController
@Setter(onMethod_ = {@Autowired})
@RequestMapping("/user")
@Slf4j
public class UserController {

    private UserService userService;


    @GetMapping("/test")
    public String test() {
        return "test";
    }

    /**
     * 登陆
     **/

    @PostMapping("/login")
    public UserDTO login(@RequestBody UserDTO userDTO) {
        return userService.login(userDTO)
                .orElseThrow(() ->
                        new UserLoginErrorException(new UserDTO().
                                setUsername(userDTO.getUsername()).setPassword(userDTO.getPassword()), userDTO.getUsername()));
    }

    @GetMapping("/")
    public List<UserDTO> getAll(int page, int size) {
        return userService.findAllUser(page, size);
    }

    @PostMapping("/insert")
    public UserDTO insert(@RequestBody UserDTO userDTO) {
        return userService.insertUser(userDTO).orElseThrow(() -> new UsernameExistException(userDTO.getUsername()));
    }

    @PostMapping("/register")
    public UserDTO register(@Validated(OnInsert.class) @RequestBody UserDTO userDTO) {
        userService.selectUserByUsername(userDTO.getUsername()).ifPresentOrElse(u -> {
            userService.register(userDTO);
        }, () -> {
            throw new UsernameExistException(userDTO.getUsername());
        });
        return userService
                .selectUserByUsername(userDTO.getUsername())
                .orElseThrow(() -> new UsernameNotFoundException(userDTO.getUsername()))
                .setPassword("");
    }

    @GetMapping("/email")
    public String testEmail() {
        return userService.testEmail("haha");
    }
}